#include "peakfilegeneratorthread.h"
#include "peakfilegenerator.h"

//
PeakFileGeneratorThread::PeakFileGeneratorThread( QFile * file, QFile * pkfile, qint64 samplPerChan, int chans, int samplPerBlock, QDataStream::ByteOrder byteOrder, DataFile::DataTypes dataType )
	:QThread(),abort(false),mainfile(file),peakfile(pkfile),samples(samplPerChan),
	channels(chans),blocksize(samplPerBlock),byteorder(byteOrder),datatype(dataType)
{
}
//
PeakFileGeneratorThread::~PeakFileGeneratorThread()
{
}
//
void PeakFileGeneratorThread::run()
{
	switch( datatype )
	{
		case DataFile::int8_t:
			generatorLoop<qint8>();
			break;
		case DataFile::uint8_t:
			generatorLoop<quint8>();
			break;
		case DataFile::int16_t:
			generatorLoop<qint16>();
			break;
		case DataFile::uint16_t:
			generatorLoop<quint16>();
			break;
		case DataFile::int32_t:
			generatorLoop<qint32>();
			break;
		case DataFile::uint32_t:
			generatorLoop<quint32>();
			break;
		case DataFile::float_t:
			generatorLoop<float>();
			break;
		case DataFile::double_t:
			generatorLoop<double>();
			break;
	}
}
//
template <class T>
int PeakFileGeneratorThread::generatorLoop()
{
	QDataStream mainstream( mainfile );
	QDataStream peakstream( peakfile );
	mainstream.setByteOrder( byteorder );
	PeakFileGenerator<T> gen( &peakstream, samples, channels, blocksize, datatype );
	T *x = new T[channels];
	mainfile->seek( 0 );
	for( qint64 i = 0; i < samples && !mainfile->atEnd(); i++ ) {
		for( int c = 0; c < channels; c++ )
			mainstream >> x[c];
		gen.processSamples( x );
		if( i % 100000 == 0 ) {
			float percent = (float)i / samples * 100;
//			qDebug( "%f", percent );
			emit progress( (int)percent );
			mutex.lock();
			if( abort ) {
				mutex.unlock();
				peakfile->remove();
				delete[] x;
				return 0;
			}
			mutex.unlock();
		}
	}
	gen.end();
	delete[] x;
	emit progress( 100 );
	return 0;
}
//
void PeakFileGeneratorThread::cancel()
{
	mutex.lock();
	abort = true;
	mutex.unlock();
}
//
